/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "tinyxml.h"

#include "hhdGUIPanel.h"
#include "hhdTScene.h"

#include "hhdContentLibrary.h"

#include "hhdMPanelTransform.h"
#include "hhdRegistry.h"

namespace hhd
{
    HObjectCPP(hhd::GUIPanel)

    GUIPanel::GUIPanel()
        : _transform2D()
        , _child_panels(16)
        , _gui_objects(16)
        , _name("")
        , _active(true)
    {
        _parent_panel = NULL;
        _parent_scene = NULL;
        depth = 0;

        registerMessageCallback<MPanelTransform>(GUIPanel::handle_panel_transform_message);
    }

    GUIPanel::~GUIPanel()
    {

    }

    GUIPanel& GUIPanel::operator=(const GUIPanel& other)
    {
        this->copy(other);
        return *this;
    }

    GUIPanel& GUIPanel::copy(const GUIPanel& in_other)
    {
        //get the transform2D
        _transform2D.copy(in_other._transform2D, this);
        //get the name
        _name = in_other._name;
        //get the parents
        _parent_panel = in_other._parent_panel;
        _parent_scene = in_other._parent_scene;
        //get depth
        depth = in_other.depth;

        //release old gui objects
        for(size_t i = 0; i < _gui_objects.size(); i++)
        {
            Factory::release(this->_gui_objects[i]);
        }
        _gui_objects.clear();

        //release old panels
        for(size_t i = 0; i < _child_panels.size(); i++)
        {
            Factory::release(this->_child_panels[i]);
        }
        _child_panels.clear();

        //get child gui objects
        //for(int k = 0; k < in_other._gui_objects.size(); k++)
        //this->addGUIObject(in_other._gui_objects[k]->clone());

        //get child panels
        for(size_t k = 0; k < in_other._child_panels.size(); k++)
        {
            this->addChildPanel(in_other._child_panels[k]->clone());
        }

        //return the copied object
        return *this;
    }

    GUIPanel* GUIPanel::clone() const
    {
        GUIPanel* result = Factory::acquire<GUIPanel>();

        result->copy(*this);

        return result;
    }


    void GUIPanel::initialize()
    {
        _active = true;

        for(size_t k = 0; k < _gui_objects.size(); k++)
        {
            _gui_objects[k]->initialize();
        }

        for(size_t j = 0; j < _child_panels.size(); j++)
        {
            _child_panels[j]->initialize();
        }

        _transform2D.initialize(this);
    }

    void GUIPanel::reset()
    {
        for(size_t i = 0; i < _child_panels.size(); i++)
        {
            Factory::release(_child_panels[i]);
        }

        for(size_t j = 0; j < _gui_objects.size(); j++)
        {
            Factory::release(_gui_objects[j]);
        }

        _parent_panel = 0;
        _parent_scene = 0;

        _child_panels.clear();
        _gui_objects.clear();
    }

    void GUIPanel::update(const GameTimer& in_gt)
    {
        //update gui objects
        size_t gui_object_count = _gui_objects.size();
        for(size_t k = 0; k < gui_object_count; k++)
        {
            _gui_objects[k]->update(in_gt);
        }

        //update gui panels
        size_t gui_panel_count = _child_panels.size();
        for(size_t k = 0; k < gui_panel_count; k++)
        {
            _child_panels[k]->update(in_gt);
        }
    }


    Transform2D& GUIPanel::getTransform2D()
    {
        return _transform2D;
    }

    const String& GUIPanel::name() const
    {
        return _name;
    }


    size_t GUIPanel::guiPanelCount() const
    {
        return _child_panels.size();
    }

    GUIPanel* GUIPanel::getChildGUIPanel(size_t in_index)
    {
        if(in_index >= _child_panels.size())
        {
            return NULL;
        }

        return _child_panels[in_index];
    }

    void GUIPanel::addChildPanel(GUIPanel* in_panel)
    {
        if(in_panel->getParentPanel() == this)
        {
            error("This object is already a child of this parent.");
        }

        in_panel->setParentPanel(this);
        in_panel->_parent_scene = _parent_scene;

        //insert the panel based on depth
        for(size_t i = 0; i < _child_panels.size(); i++)
        {
            if(in_panel->depth > _child_panels[i]->depth)
            {
                _child_panels.insert(i, in_panel);
                return;
            }
        }
        //panel appended at the end of the list
        _child_panels.add(in_panel);
    }

    GUIPanel* GUIPanel::getChildPanelByName(const String& in_name)
    {
        for( size_t i = 0; i < _child_panels.size(); i++ )
        {
            if(_child_panels[i]->_name == in_name)
            {
                return _child_panels[i];
            }
        }
        for( size_t i = 0; i < _child_panels.size(); i++ )
        {
            GUIPanel* result = _child_panels[i]->getChildPanelByName(in_name);
            if(result)
            {
                return result;
            }
        }
        return NULL;
    }

    size_t GUIPanel::guiObjectCount() const
    {
        return _gui_objects.size();
    }

    IGUIObject* GUIPanel::getGUIObject(size_t in_index)
    {
        if(in_index >= _gui_objects.size())
        {
            return NULL;
        }

        return _gui_objects[in_index];
    }

    void GUIPanel::addGUIObject(IGUIObject* in_gui_object)
    {
        in_gui_object->_parent_panel = this;
        _gui_objects.add(in_gui_object);
    }

    GUIPanel* GUIPanel::getParentPanel()
    {
        return _parent_panel;
    }

    void GUIPanel::setParentPanel(GUIPanel* in_panel)
    {
        _parent_panel = in_panel;
    }

    TScene* GUIPanel::getScene()
    {
        return _parent_scene;
    }

    void GUIPanel::setScene(TScene* in_scene)
    {
        _parent_scene = in_scene;

        for(size_t i = 0; i < _child_panels.size(); i++)
        {
            _child_panels[i]->setScene(in_scene);
        }
    }


    GUIPanel* GUIPanel::readXML(const String& in_xml, IHObject* in_owner)
    {
        TiXmlDocument document;
        document.Parse(in_xml);

        TiXmlElement* node = document.RootElement();

        if(node)
        {
            //check to see if our owner is a scene, if so record it
            if(in_owner->is<TScene>())
            {
                _parent_scene = in_owner->as<TScene>();
            }
            else
            {
                _parent_scene = NULL;
            }


            //get a name from file, or if not given, generate one
            const char* name = node->Attribute("name");
            this->_name = name;


            //get the position and depth data, otherwise it is defaulted already
            Vector2 panelPosition;
            node->QueryVector2Attribute("position", &panelPosition);
            _transform2D.setTranslation(panelPosition.x, panelPosition.y);
            node->QueryIntAttribute("depth", &depth);


            // this method is used to add gui panels to the dictionary so we can get gui panels by name
            if(this->_parent_scene != NULL)
            {
                this->_parent_scene->addGUIPanel(this);
            }


            //go for child components and child gui objects
            TiXmlNode* child = 0;
            while( (child = node->IterateChildren(child)) )
            {
                TiXmlElement* child_element = child->ToElement();
                if(!child_element) // probably a comment but more importantly not parseable as an element
                {
                    continue;
                }

                String tag(child_element->Value());

                if(tag.equals("GUIPanel"))
                {
                    String go_xml(*child_element);

                    GUIPanel* gp = Factory::acquire<GUIPanel>();
                    gp->readXML(go_xml, in_owner);
                    this->addChildPanel(gp);
                }
                else if(tag.equals("Component"))
                {
                    const char8_t* component_type = child_element->Attribute("type");
                    if(component_type != NULL)
                    {
                        // get the prototype from the index so we can parse
                        IComponent* prototype = Registry<IComponent>::createFromRegistry(component_type);

                        if(prototype == NULL)
                        {
                            StringBuilder sb;
                            sb << "Couldn't find Prototype for component \"" << component_type << "\"" << endl;
                            sb << "Have you registered it in the ComponentIndex?" << endl;
							String string;
							sb >> string;
                            error(string);
                        }

                        // now get a new instance of the prototype from the factory
                        IGUIObject* new_component = (IGUIObject*)Factory::acquire(prototype);

                        // dump xml to string
                        String co_xml(*child_element);

                        // parse it!
                        this->addGUIObject(new_component);
                        new_component->readXML(co_xml);
                    }
                }
            }
        }

        return this;
    }


    void GUIPanel::handle_panel_transform_message(IMessageReceiver* receiver, IMessage* message)
    {
        GUIPanel* target = (GUIPanel*)receiver;

        if(MPanelTransform* ptf = message->as<MPanelTransform>())
        {
            target->_transform2D.translate(ptf->translation.x, ptf->translation.y);
            target->_transform2D.rotate(ptf->rotation);
            target->_transform2D.scale(ptf->scale.x, ptf->scale.y);
        }
    }

    void GUIPanel::setActivity(bool in_activity)
    {
        _active = in_activity;

        for(size_t i = 0; i < _gui_objects.size(); i++)
        {
            _gui_objects[i]->setActivity(in_activity);
        }

        for(size_t i = 0; i < _child_panels.size(); i++ )
        {
            _child_panels[i]->setActivity(in_activity);
        }
    }

    bool GUIPanel::getActivity()
    {
        return _active;
    }
}
